﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GestionePolveriLib.Facades;
using BrightIdeasSoftware;
using GestionePolveriLib.BL;
using GestionePolveriLib.Utilities;

namespace GestionePolveri2
{
    public partial class AssociaPolvereDialog : Form
    {
        private List<PolvereExt> m_polveri = null;
        private List<Colore> m_colori = null;
        private ComposizioneColore2 m_formula = null;
        private ComposizioneColoreExt dataExt = null;
        private List<PolvereExt> m_polveriSelezionate = null;

        public ComposizioneColoreExt ComposizioneFormula
        {
            get { return dataExt; }
            set { dataExt = value; }
        }

        public ComposizioneColore2 Formula 
        {
            get { return m_formula; }
            set 
            { 
                m_formula = value;

                ModifyFormula(m_formula);
            } 
        }

        public bool IsNew { get; set; }
        public bool IsModified { get; set; }

        public List<Colore> Colori
        {
            get { return m_colori; }
            set { m_colori = value; }
        }

        public List<PolvereExt> Polveri
        {
            get { return m_polveri; }
            internal set { m_polveri = value; }
        }

        public AssociaPolvereDialog()
        {
            InitializeComponent();

            if (!DesignMode)
            {
                //LoadPolveri();
                //LoadColori();

                m_colori = new List<Colore>();
                m_polveri = new List<PolvereExt>();

                FilterComboBoxHelper.SetupColoriComboBoxAssociaPolvere(this.cmbColori);
                FilterComboBoxHelper.SetupPolveriComboBoxAssociaPolvere(this.cmbPolveri);

                this.cmbColori.KeyDown += new KeyEventHandler(cmbColori_KeyDown);
                this.cmbPolveri.KeyDown += new KeyEventHandler(cmbPolveri_KeyDown);

                this.btnChooseColor.Click += new EventHandler(btnChooseColor_Click);
                this.btnChoosePolvere.Click += new EventHandler(btnChoosePolvere_Click);

                this.btnDeleteColore.Click += new EventHandler(btnDeleteColore_Click);
                this.btnDeletePolvere.Click += new EventHandler(btnDeletePolvere_Click);
            }
        }

        public AssociaPolvereDialog(bool modified)
        {
            InitializeComponent();

            IsModified = modified;

            this.cmbColori.Enabled = false;
            this.btnChooseColor.Enabled = false;
            this.btnDeleteColore.Enabled = false;

            FilterComboBoxHelper.SetupPolveriComboBoxAssociaPolvere(this.cmbPolveri);

            this.cmbPolveri.KeyDown += new KeyEventHandler(cmbPolveri_KeyDown);
            this.btnChoosePolvere.Click += new EventHandler(btnChoosePolvere_Click);
            this.btnDeletePolvere.Click += new EventHandler(btnDeletePolvere_Click);

            if (!DesignMode)
            {
                m_colori = new List<Colore>();
                m_polveri = new List<PolvereExt>();
            }
        }

        void btnDeletePolvere_Click(object sender, EventArgs e)
        {
            OLVListItem item = this.objectListViewPolveri.SelectedItem;

            if (item != null)
            {
                this.objectListViewPolveri.Items.Remove(item);

            }
        }

        void btnDeleteColore_Click(object sender, EventArgs e)
        {
            OLVListItem item = this.objectListViewColori.SelectedItem;

            if (item != null)
              this.objectListViewColori.Items.Remove(item);
        }

        void btnChoosePolvere_Click(object sender, EventArgs e)
        {
            ChoosePolvere();
        }

        void btnChooseColor_Click(object sender, EventArgs e)
        {
            ChooseColore();
        }

        void cmbPolveri_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                ChoosePolvere();
            }
        }

        void cmbColori_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                ChooseColore();
            }
        }

        private void ChoosePolvere()
        {
            PolvereExt c = (PolvereExt)this.cmbPolveri.SelectedItem;

            List<PolvereExt> result = (List<PolvereExt>)this.objectListViewPolveri.Objects;
            if (result == null)
            {
                result = new List<PolvereExt>();
            }

            result.Add(c);

            this.objectListViewPolveri.SetObjects((List<PolvereExt>)result);
            foreach (OLVListItem item in this.objectListViewPolveri.Items)
            {
                this.objectListViewPolveri.ToggleCheckObject(item.RowObject);
            }
        }

        private void ChooseColore()
        {
            Colore c = (Colore)this.cmbColori.SelectedItem;

            List<Colore> result = (List<Colore>)this.objectListViewColori.Objects;
            if (result == null)
            {
                result = new List<Colore>();
            }

            result.Add(c);

            this.objectListViewColori.SetObjects((List<Colore>)result);
            foreach (OLVListItem item in this.objectListViewColori.Items)
            {
                this.objectListViewColori.ToggleCheckObject(item.RowObject);
            }
        }

        private void LoadColori()
        {
            ColoriFacade fcf = new ColoriFacade();
            fcf.RunAsync(() => fcf.GetAllEssential(), (result) =>
            {
                this.objectListViewColori.AddDecoration(new EditingCellBorderDecoration { UseLightbox = true });
                this.objectListViewColori.SetObjects((List<Colore>)result);
            });
        }

        private void LoadPolveri()
        {
            PolvereFacade fcf = new PolvereFacade();
            fcf.RunAsync(() => fcf.GetAllEssential(), (result) =>
            {
                this.objectListViewPolveri.AddDecoration(new EditingCellBorderDecoration { UseLightbox = true });
                this.objectListViewPolveri.SetObjects((List<PolvereExt>)result);
            });
        }

        private void ModifyFormula(ComposizioneColore2 formula)
        {
            ComposizioneColoreFacadeExt ccfext = new ComposizioneColoreFacadeExt();
            List<PolvereExt> m_polveriAssociate = ccfext.GetPolveriAssociate(formula.Colore.ID);

            this.objectListViewColori.Items.Clear();
            this.objectListViewPolveri.Items.Clear();

            List<Colore> m_colori = new List<Colore>();
            m_colori.Add(m_formula.Colore);
            this.objectListViewColori.SetObjects(m_colori);
            this.objectListViewPolveri.SetObjects(m_polveriAssociate);

            foreach (OLVListItem item in this.objectListViewColori.Items)
            {
                this.objectListViewColori.ToggleCheckObject(item.RowObject);
            }

            foreach (OLVListItem item in this.objectListViewPolveri.Items)
            {
                this.objectListViewPolveri.ToggleCheckObject(item.RowObject);
            }
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            this.btnOk.DialogResult = System.Windows.Forms.DialogResult.None;

            if (ValidateData())
            {
                foreach (Colore c in this.objectListViewColori.CheckedObjects)
                {
                    m_colori.Add(c);
                }

                foreach (PolvereExt p in this.objectListViewPolveri.CheckedObjects)
                {
                    if (p.Base && p.Venatura)
                    {
                        // caso particolre in cui la polvere è sia base che venatura...
                        p.Base = true;
                        p.Venatura = false;
                        m_polveri.Add(p);

                        PolvereExt p1 = (PolvereExt)p.Clone();
                        p1.Base = false;
                        p1.Venatura = true;
                        m_polveri.Add(p1);
                    }
                    else
                    {
                        m_polveri.Add(p);
                    }
                }

                //if (this.IsModified)
                //{
                dataExt = new ComposizioneColoreExt();
                dataExt.Colore = m_colori[0];
                dataExt.Polveri = m_polveri;
                //}


                if (CheckFormulaDuplicated(dataExt) && !IsModified)
                {
                    m_polveri.Clear();
                    this.btnOk.DialogResult = System.Windows.Forms.DialogResult.None;
                    MessageBox.Show("Formula Duplicata. Una Formula con le stesse impostazioni di colore e polvere è già esistente !", "Gestione Polveri", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                else
                {
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                    //this.btnOk.DialogResult = System.Windows.Forms.DialogResult.OK;
                    this.Close();
                }
            }
            else
            {
                this.btnOk.DialogResult = System.Windows.Forms.DialogResult.None;
                MessageBox.Show("Verificare che le polveri nell'elenco siano definite come BASE o come VENATURA !", "Gestione Polveri", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private bool ValidateData()
        {
            bool retValue = true;

            if(this.objectListViewColori.CheckedObjects.Count == 0)
            {
                MessageBox.Show("Selezionare il colore presente nell'elenco !", "Gestione Polveri", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                retValue = false; 
            }

            foreach (PolvereExt polvere in this.objectListViewPolveri.CheckedObjects)
            {
                //PolvereExt polvere = (PolvereExt)item.RowObject;

                //if ((!polvere.Base && !polvere.Venatura) || (polvere.Base && polvere.Venatura))
                if (!polvere.Base && !polvere.Venatura)
                {
                    retValue = false;
                    break;
                }
            }

            return retValue;
        }

        private bool CheckFormulaDuplicated(ComposizioneColoreExt data)
        {
            bool retValue = false;

            ComposizioneColoreFacadeExt ccfExt = new ComposizioneColoreFacadeExt();
            retValue = ccfExt.CheckDuplicate(data);

            return retValue;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtCerca_TextChanged(object sender, EventArgs e)
        {
            TextMatchFilter filter = null;
            if (!String.IsNullOrEmpty(txtCerca.Text))
            {
                filter = TextMatchFilter.Prefix(this.objectListViewPolveri, txtCerca.Text);

                objectListViewPolveri.AdditionalFilter = filter;

                //switch (matchKind)
                //{
                //    case 0:
                //    default:
                //        filter = TextMatchFilter.Contains(olv, txt);
                //        break;
                //    case 1:
                //        filter = TextMatchFilter.Prefix(olv, txt);
                //        break;
                //    case 2:
                //        filter = TextMatchFilter.Regex(olv, txt);
                //        break;
                //}
            }
            else
            {
                objectListViewPolveri.AdditionalFilter = null;
            }
        }

        private void txtCercaColore_TextChanged(object sender, EventArgs e)
        {
            TextMatchFilter filter = null;
            if (!String.IsNullOrEmpty(txtCercaColore.Text))
            {
                filter = TextMatchFilter.Prefix(this.objectListViewColori, txtCercaColore.Text);

                //this.objectListViewColori.ModelFilter = new OnlyEmergenciesFilter(txtCercaColore.Text);
                
                objectListViewColori.AdditionalFilter = filter;
            }
            else
            {
                objectListViewColori.AdditionalFilter = null;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            NewPolvereElenco npe = new NewPolvereElenco();
            if (npe.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (npe.PolveriSelezionate.Count > 0)
                {
                    if(m_polveriSelezionate == null)
                      m_polveriSelezionate = new List<PolvereExt>();
                    
                    //foreach (OLVListItem item in this.objectListViewPolveri.Items)
                    //{
                    //    m_polveri.Add((PolvereExt)item.RowObject);
                    //}

                    m_polveri.AddRange(npe.PolveriSelezionate);

                    this.objectListViewPolveri.Items.Clear();
                    this.objectListViewPolveri.SetObjects(m_polveri);

                    foreach (OLVListItem item in this.objectListViewPolveri.Items)
                    {
                        this.objectListViewPolveri.ToggleCheckObject(item.RowObject);
                    }
                }
            }
        }

        
    }

    public class OnlyEmergenciesFilter : IModelFilter
    {
        private string m_textToSearch = string.Empty;

        public OnlyEmergenciesFilter(string textToSearch)
        {
            m_textToSearch = textToSearch;
        }

        public bool Filter(object modelObject)
        {
            return ((Colore)modelObject).CodiceColore.StartsWith(m_textToSearch);
        }
    }

}
